<?php 

namespace app\admin\controller;

use app\lib\Qiniu;
use app\common\BaseHelper;

use think\Db;
use think\Controller;
use think\Request;

/**
 * 处理图片类
 * @package app\admin\controller
 */
class Image extends Controller
{

	/**
	 * 获取七牛token
	 */
	public function token() {
		$Qiniu = new Qiniu();

		return json([
		    'uptoken' => $Qiniu->getToken()
        ]);
	}

	/**
	 * 将上传的每一张图片记录到数据表中
	 */
	public function record() {
		$controller = 'test';
        $id = BaseHelper::getUUID();
        $data = [
            'id' => $id,
            'img_url' => $_POST['imgUrl'],
            'controller' => $controller,
            'created' => time()
        ];

        $result = Db::name('image')->insert($data);
        $code = $result ? '1' : '2';

        return json(['image_id' => $id, 'code' => $code]);
	}

	/**
	 * 图片删除-删除记录及七牛空间中的图片
	 */
	public function delete() {
		$id = $this->request->param('id');
		$url = $this->request->param('imgUrl');
		$key =  substr(strrchr($url, '/'), 1);

		$Qiniu = new Qiniu();
        // 删除图片
		$result = $Qiniu->delImg($key);
		if($result == null){
			//Db::table('image')->where('id',$id)->delete();  //删除总表记录
            Db::name('image')->where('img_url', $url)->delete();  // 删除总表记录

            return json(['code'=>'1', 'message' => 'success']);
        }else{
            return json(['code'=>'2', 'message'=>'删除失败']);
        }
	}

}